package com.example.springdeepseek.controller;

import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.Map;

/**
 * 对接DeepSeek后生成回答的Controller
 */
@RestController
public class DeepSeekController {
    private final OpenAiChatModel chatModel;

    @Autowired
    public DeepSeekController(OpenAiChatModel chatModel) {
        this.chatModel = chatModel;
    }

    /**
     * 根据消息直接输出回答
     * http :8080/ai/chat?message="你好，给我生成一首诗词"
     * Example Response:
     * {
     * "generation": "《七绝·江畔春深》\n暮云漫卷掩余晖，碧浪推舟鸥鹭飞。\n夹岸青山遮望眼，忽闻空谷响春雷。\n\n赏析：这首作品描绘江畔暮春之景，以“暮云”、“碧波”、“ 意之惊雷，于无声处听惊雷，于暮色中觅 生机。"
     * }
     */
    @GetMapping("/ai/chat")
    public Map chat(@RequestParam(value = "message") String message) {
        return Map.of("generation", this.chatModel.call(message));
    }

    /**
     * 根据消息采用流式输出，输出回答
     * http :8080/ai/chatFlux?message="你好，你能通过图灵测试吗"
     * Response:
     * "result": {
     * "metadata": {
     * "contentFilters": [],
     * "empty": true,
     * "finishReason": ""
     * },
     * "output": {
     * "media": [],
     * "messageType": "ASSISTANT",
     * "metadata": {
     * "annotations": [],
     * "finishReason": "",
     * "id": "chatcmpl-0686c1ba-79e1-9388-a4a8-c45d94ba9e20",
     * "index": 0,
     * "messageType": "ASSISTANT",
     * "refusal": "",
     * "role": "ASSISTANT"
     * },
     * "text": "官方",
     * "toolCalls": []
     * }
     * },
     * "results": [
     * {
     * "metadata": {
     */
    @GetMapping(value = "/ai/chatFlux", produces = MediaType.TEXT_EVENT_STREAM_VALUE + "; charset=UTF-8")
    public Flux<ChatResponse> chatFlux(@RequestParam(value = "message") String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return this.chatModel.stream(prompt);
    }
}
